//服务端

var cons = new Array();
var userArray = new Array();
var WebSocketServer = require('ws').Server,
    wss = new WebSocketServer({port:8080});

wss.on('connection',function(ws){
    //从头中取出客户端标示userid，当然也可以得到客户端的ip地址
    var userId = ws.upgradeReq.headers['userid'];
    console.log('new connection successfully userId:'+userId);
    cons.push(ws);
    userArray.push(userId);
    ws.on('message',function(message){
        console.log(message);
        for (var i=0; i<cons.length;i++) {
            //判断userid是否为toUserId（发给指定的客户端）
            var msgObj = JSON.parse(message);
            if (userArray[i] == msgObj.toUserId) {
                cons[i].send(message);
                break;
            }
        }
    });
    ws.on('close',function(){
        for (var i=0;i<cons.length;i++){
            if (cons[i]==ws)cons.splice(i,1);
        }
    });
});

console.log('websocket-server running...');